<?php
/**
 * Created by PhpStorm.
 * User: Hong
 * Date: 2018/3/9
 * Time: 14:40
 * Function:
 */

namespace Platform\Models\Organize;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;

class LeaderPermission extends Model
{
    protected $table = 'leader_permissions';

    /**
     * @var array
     */
    protected $fillable = [
        'module', 'name', 'level', 'method', 'uri', 'controller', 'action', 'route_name'
    ];


    /**
     * 绑定角色表关系
     * @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
     */
    public function roles() : BelongsToMany
    {
        return $this->belongsToMany(LeaderRole::class, 'leader_role_permissions', 'permission_id', 'role_id');
    }

    /**
     * 拼接权限列表的数据，标记目标管理员已有权限
     * @param $permissions
     * @param $admin_permissions
     * @return array
     */
    public static function makeData($permissions,$admin_permissions = [])
    {
        foreach ($permissions as $key => $permission){
            $permissions[$key]['is_have'] = 0;
            foreach ($permission->toPermissions() as $method => $uri){
                if (empty($admin_permissions[$method])) continue;

                if (in_array($uri,$admin_permissions[$method])){
                    $permissions[$key]['is_have'] = 1;
                }else continue;
            };
            if (!empty($permission['uri'])) unset($permission['uri']);
            if (!empty($permission['method'])) unset($permission['method']);
        }

        $data = [];
        foreach ($permissions as $key => $permission){
            $data[$permission['module']]['routes'][] = $permission;
            $data[$permission['module']]['module'] = $permission['module'];
        }
        $data = array_values($data);
        return $data;
    }

    /**
     * 将路由根据访问方法归类
     * GET|POST /admin/users =>
     * array(
        GET => /admin/users
        POST => /admin/users
     * )
     * @return array
     */
    public function toPermissions()
    {
        $methods = explode('|', $this->method);

        $permissions = [];
        foreach ($methods as $method) {
            $permissions[$method] = $this->uri;
        }

        return $permissions;
    }

    /**
     * 刷新缓存的权限
     */
    public static function refreshCache()
    {
        $admins = Leader::all();
        foreach ($admins as $key => $admin){
            $admin->savePermissions();
        }
    }
}